﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using AMS.Core.Data;

namespace AMS.DD35.DbAccess.SqlClient
{
    public class SqlLoginConnector : ILoginConnector
    {
        IConfiguration _config;

        public SqlLoginConnector(IConfiguration configuration)
        {
            _config = configuration;
        }

        public bool VerifyUsernamePassword(LoginData loginData)
        {
            using (SqlConnection conn = new SqlConnection(_config.ConnectionString))
            {
                string commandString = String.Format("SELECT password_hash FROM {0}.{1}.Users WHERE username=@username", _config.Database, _config.Schema);
                using (SqlCommand command = new SqlCommand(commandString, conn))
                {
                    command.Parameters.AddWithValue("@username", loginData.Username);
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dataReader = command.ExecuteReader())
                        {
                            while (dataReader.Read())
                            {
                                string storedHash = Convert.ToString(dataReader["password_hash"]);
                                return loginData.PasswordHash == storedHash;
                            }
                        }
                    }
                    catch (SqlException ex)
                    {
                        throw new Exception("logon failed", ex);
                    }
                }
            }

            throw new Exception("logon failed");
        }
    }
}
